package top.lingkang.mm;

import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import top.lingkang.mm.gen.DefaultIdGenerate;
import top.lingkang.mm.orm.MapperManage;
import top.lingkang.mm.override.MagicReflectorFactory;
import top.lingkang.mm.page.MagicPageInterceptor;

/**
 * @author lingkang
 * @create by 2024/3/4 9:53
 */
@ConditionalOnSingleCandidate(SqlSessionFactory.class)
public class MybatisMagicAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(MybatisMagicAutoConfiguration.class);

    @Bean
    public MapperManage mapperManage(@Autowired SqlSessionFactory sqlSessionFactory,
                                     @Autowired SqlSessionTemplate sessionTemplate) {
        SpringMapperManage manage = new SpringMapperManage(sqlSessionFactory.getConfiguration(), sessionTemplate);
        ReflectorFactory reflectorFactory = sqlSessionFactory.getConfiguration().getReflectorFactory();
        if (reflectorFactory instanceof DefaultReflectorFactory) {
            sqlSessionFactory.getConfiguration().setReflectorFactory(new MagicReflectorFactory());
            log.debug("加载反射工厂完成");
        }
        sqlSessionFactory.getConfiguration().addInterceptor(new MagicPageInterceptor());
        log.debug("加载分页拦截完成");
        manage.setIdGenerate(new DefaultIdGenerate());
        if (!sqlSessionFactory.getConfiguration().isMapUnderscoreToCamelCase()) {
            log.info("建议开启下划线转驼峰, 以获得增强体验, application.properties 中添加: mybatis.configuration.map-underscore-to-camel-case=true");
        }
        return manage;
    }
}
